package in.muton.edushare.panels.folder;

import java.util.List;

import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;

import com.edushare.common.dao.FileDirectoriesDAO;
import com.edushare.common.vo.FileDirectories;

import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.pages.folder.FolderHelper;

public class ChangeFolderVisibilityPanel extends EdusharePanel {

	private static final long serialVersionUID = -8258007475994363666L;
	private IModel<FileDirectories> model;

	public ChangeFolderVisibilityPanel(String id, IModel<FileDirectories> model, EduShareBasePage page) {
		super(id, model, page);
		this.model = model;
		add(CSSPackageResource.getHeaderContribution(ChangeFolderVisibilityPanel.class, "ChangeFolderVisibilityPanel.css"));
		List<String> allowedVis = FileDirectories.getAllPermissions(model.getObject().getOwnerType());
		FileDirectories parent = model.getObject().getParent();
		if(parent!=null)//non-root dir
		{
			allowedVis = FileDirectories.getValidFilePermissions(parent);
		}
		ListView<String> lv = new ListView<String>("visItem", allowedVis) {

			@Override
			protected void populateItem(final ListItem<String> item) {
				SubmitLink changeTo = new SubmitLink("visLink"){
					@Override
					public void onSubmit() {
						new FileDirectoriesDAO(getORMInterface())
						.updateFolderAndSubfolderVisibility
						(ChangeFolderVisibilityPanel.this.model.getObject(), 
						item.getModelObject());
					}
				};
				changeTo.setDefaultFormProcessing(false);
				changeTo.add(new Label("visText", FolderHelper.getFolderReadPermissionString(item.getModelObject())));
				item.add(changeTo);
				if(item.getModelObject().equals(ChangeFolderVisibilityPanel.this.model.getObject().getReadPerm())){;
					changeTo.setEnabled(false);
				}
			}
		};
		
		Form<Void> f = new Form<Void>("changeVisForm");
		f.add(lv);
		add(f);
	}

}
